package gfun

import (
	"golang.org/x/sys/windows/registry"
	"io"
	"net/http"
	"os"
	"os/exec"
	"syscall"
)

// IsWebView2Installed 检测WebView2是否安装
func IsWebView2Installed() bool {
	k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}`, registry.QUERY_VALUE)
	if err != nil {
		return false
	}
	defer k.Close()

	_, _, err = k.GetStringValue("pv")
	return err == nil
}

// InstallWebView2 下载并安装WebView2运行时
func InstallWebView2() error {
	url := "https://go.microsoft.com/fwlink/p/?LinkId=2124703"
	outPath := "$TEMP\\MicrosoftEdgeWebview2Setup.exe"

	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	outFile, err := os.Create(outPath)
	if err != nil {
		return err
	}
	defer outFile.Close()

	_, err = io.Copy(outFile, resp.Body)
	if err != nil {
		return err
	}

	cmd := exec.Command(outPath, "/silent", "/install")
	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
	return cmd.Run()
}
